package cn.openea.perpartner.meily.web.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.openea.perpartner.common.core.utils.poi.ExcelUtil;
import cn.openea.perpartner.common.core.web.controller.BaseController;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.common.core.web.page.TableDataInfo;
import cn.openea.perpartner.meily.web.entity.Customer;
import cn.openea.perpartner.meily.web.entity.dto.CustomerDTOFactory;
import cn.openea.perpartner.meily.web.entity.vo.CustomerBatchVo;
import cn.openea.perpartner.meily.web.entity.vo.CustomerRecommendVo;
import cn.openea.perpartner.meily.web.entity.vo.CustomerSearchVo;
import cn.openea.perpartner.meily.web.service.ICustomerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author ysk
 * @email zane_ysk@qq.com
 * @date 2023-04-27 19:04:05
 */
@Api(tags = "平台用户管理")
@RestController
@RequestMapping("/customer")
public class CustomerController extends BaseController {

    @Resource
    private ICustomerService customerService;
    @Resource
    private CustomerDTOFactory customerDTOFactory;

    @ApiOperation("分页查询用户列表")
    @GetMapping("/page/list")
    public AjaxResult pageList(CustomerSearchVo searchVo) {
        startPage();
        List<Customer> customerList = customerService.selectListByVO(searchVo);
        TableDataInfo dataTable = getDataTable(customerList);
        Map<String, Object> data = new HashMap<>();
        data.put("list", customerList.stream()
                .map(item -> customerDTOFactory.toBasicInfoDTO.apply(item))
                .collect(Collectors.toList()));
        data.put("total", dataTable.getTotal());
        if (searchVo.isAllStatistics()) {
            // 统计相关数据
            data.put("customerTypeQuantity", customerService.statisticsCustomerTypeQuantity(searchVo));
        }
        return AjaxResult.success(data);
    }

    @ApiOperation("根据Id获取用户详情")
    @GetMapping("/info/{id}")
    public AjaxResult getInfoById(@PathVariable String id) {
        if (StringUtils.isBlank(id)) {
            return AjaxResult.error("数据异常，编号为空");
        }
        Customer customer = customerService.getById(id);
        return AjaxResult.success(customerDTOFactory.toAllInfoDTO.apply(customer));
    }

    @ApiOperation("根据平台ID获取用户详情")
    @GetMapping("/user/{userId}/info/")
    public AjaxResult getInfoByUserId(@PathVariable String userId) {
        if (StringUtils.isBlank(userId)) {
            return AjaxResult.error("用户不存在");
        }
        Customer customer = customerService.findByUserId(userId);
        return AjaxResult.success(customerDTOFactory.toAllInfoDTO.apply(customer));
    }

    @ApiOperation("导出用户")
    @PostMapping("/export/excel")
    public void exportCustomerExcel(@RequestBody CustomerBatchVo batchVo, HttpServletResponse response) {
        List<Customer> customerList;
        if (batchVo.byIds()) {
            // 根据id去查
            customerList = customerService.selectByIds(batchVo.getBatchIds());
        } else {
            customerList = customerService.selectListByVO(batchVo.getQueryVO());
        }
        List<CustomerDTOFactory.CustomerExportExcelDTO> exportExcelDTOS = customerList
                .parallelStream()
                .map(item -> customerDTOFactory.toExportExcelDTO.apply(item))
                .collect(Collectors.toList());
        // 导出
        ExcelUtil<CustomerDTOFactory.CustomerExportExcelDTO> util = new ExcelUtil<>(CustomerDTOFactory.CustomerExportExcelDTO.class);
        util.exportExcel(response, exportExcelDTOS, "平台用户列表.xlsx");
    }

    @ApiOperation("小程序-获取个人基本信息")
    @GetMapping("/applet/info/{userId}")
    public AjaxResult getInfo(@PathVariable String userId) {
        if (StringUtils.isBlank(userId)) {
            return AjaxResult.error("数据异常，用户id为空！");
        }
        Customer customer = customerService.findByUserId(userId);
        if (customer == null || BeanUtil.isEmpty(customer)) {
            AjaxResult.error("用户不存在!");
        }
        return AjaxResult.success("获取基本信息成功！", customer);
    }

    @ApiOperation("小程序-更新个人基本信息")
    @PostMapping("/applet/update")
    public AjaxResult update(@RequestBody Customer customer) {
        if (!customerService.update(customer)) {
            return AjaxResult.error("保存失败！");
        }
        return AjaxResult.success("保存成功！");
    }

    @ApiOperation("小程序-个人基本信息是否完善")
    @GetMapping("/applet/finish/{userId}")
    public AjaxResult finish(@PathVariable String userId) {
        if (!customerService.finish(userId)) {
            return AjaxResult.error("资料未完善", false);
        }
        return AjaxResult.success("资料已完善", true);
    }

    @ApiOperation("修改用户信息")
    @PostMapping("/update/customer")
    public AjaxResult updateCustomer(@RequestBody CustomerDTOFactory.CustomerAllInfoDTO dto){
        customerService.updateCustomerByDTO(dto);
        return AjaxResult.success();
    }

    @ApiOperation("为你推荐")
    @PostMapping("/recommend/list")
    public TableDataInfo recommend(@RequestBody CustomerRecommendVo vo){
        startPage();
        List<Customer> list = this.customerService.recommend(vo);
        TableDataInfo dataInfo = getDataTable(list);
        dataInfo.setRows(this.customerService.assemblyData(list, vo.getSearchType()));// 组装业务数据
        return dataInfo;
    }
}
